<template>
  <el-form
    ref="formRef"
    label-width="50%"
    :model="recombValue"
    :label-position="props.editor ? 'top' : 'right'"
    :hide-required-asterisk="!props.editor"
  >
    <el-row :gutter="40">
      <template v-for="item in recombItems">
        <el-col :span="props.span">
          <merak-control
            v-bind="item"
            v-model="recombValue[item.field]"
            :ref="el => (recombRefs[item.field] = el as MerakControlInstance)"
            :default-selected-label="recombValue[`${item.field}_txt`]"
            :query-options="recombQueryOptions"
            @change="recombChange"
          >
            <template v-for="prefix in Object.keys(recombPrefix)" #[prefix]>{{ recombPrefix[prefix] }}_</template>
          </merak-control>
        </el-col>
      </template>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { BlockKeys, BlockRefs } from "../index";

import { inject, ref, reactive } from "vue";

import { useRoute } from "vue-router";

import useProductForm from "@/hooks/useProductForm";

import { ElRow, ElCol, ElForm } from "element-plus";

import MerakControl, { MerakControlInstance, MerakControlProps, MerakControlOption } from "@/components/MerakControl";

const props = defineProps<{
  // 初始化请求队列 id
  queueId?: string;
  // 表单项动态列数
  span: number;
  // 编辑状态
  editor: boolean;
  // 渲染数据
  info: MerakControlProps[];
  // 表单数据
  data: Record<string, any>;
  // 只读字段
  readonly: Array<string>;
}>();

const route = useRoute();

const blocks = inject<BlockRefs>("blocks");

const formRef = ref<InstanceType<typeof ElForm>>();

const state = reactive<{}>({});

const linkage = (field: string, value: any) => {
  const linkageMap: Record<string, () => void> = {};
  linkageMap[field]?.();
};

const { recombRefs, recombPrefix, recombValue, recombItems, recombQueryOptions, recombChange, recombRecord, recombReduction } =
  useProductForm({
    typeId: (route.query.t_id ?? 1).toString(),
    suite: route.query.s_id === "1" ? 1 : 0,
    queueId: () => props.queueId,
    editor: () => props.editor,
    formItems: () => props.info,
    formData: () => props.data,
    readonlyKeys: () => props.readonly,
    linkage
  });

defineExpose({
  handleEdit: () => recombRecord(),
  handleCancel: () =>
    recombReduction().then(() => {
      formRef.value?.clearValidate();
      return Promise.resolve();
    }),
  handleSave: () => formRef.value?.validate().then(() => Promise.resolve(recombValue)),
  closePanel: () => {
    Object.values(recombRefs).forEach(ref => ref.closePopover());
  }
});
</script>

<style scoped lang="scss"></style>
